package cj.web.pay.controllers;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Post;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.parser.XmlTreeBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.weixin.pay.PayConstants;
import cj.web.constants.PayWayEnum;
import cj.web.constants.SCOrderStatusEnum;
import cj.web.constants.WXPayAttachEnum;
import cj.web.sc.dao.OrderDAO;

@Path("wxNotify")
public class WxNotifyController {
	@Autowired
	private OrderDAO orderDao;
	
	/***
	 * 微信支付异步回调接口
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Post("result")
	public void wxNotify(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			InputStream inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			inStream.close();
			String resultStr = new String(outSteam.toByteArray(), "utf-8");
			Map<String, String> resultMap = analysisRssHead(resultStr);
			String result_code = resultMap.get("result_code");
			
			if (PayConstants.SUCCESS.equals(result_code)) {
				//微信支付订单号
				String transaction_id = resultMap.get("transaction_id");
				
				//商户订单号
				String out_trade_no = resultMap.get("out_trade_no");
				
				//订单来源，是商城订单还是报名订单
				String orderSource = resultMap.get("attach");
				
				//修改订单状态为已付款，加入微信支付单号
				wxTradeSuccess(out_trade_no, transaction_id, orderSource);
				
				// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
				response.getWriter().write(setXML("SUCCESS", "OK"));
			} else {
				response.getWriter().write(setXML("FAIL", "FAIL"));
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void wxTradeSuccess(String out_trade_no, String transaction_id,
			String orderSource) {
		if(orderSource.equals(WXPayAttachEnum.SC.getValue())){  //商城
			//修改订单状态为已付款，加入微信支付单号
			orderDao.updateStatusByNO(SCOrderStatusEnum.paid.getValue(), out_trade_no, transaction_id,PayWayEnum.WX.getValue()); 
			int orderId = orderDao.getIdByOrderNo(out_trade_no);
			List<Map> items = orderDao.getItemsByOrderId(orderId);
			//修改商品数量
			for(Map item : items){
				int id = Integer.parseInt(item.get("goodsItemId").toString());
				int count = Integer.parseInt(item.get("count").toString());
				orderDao.updateGoodsItemCnt(id, count);
			}
		}
	}

	private Map<String, String> analysisRssHead(String resultStr)
	{
		Document doc = Jsoup.parse(resultStr, "", new Parser(new XmlTreeBuilder()));
		
		Element xml = doc.getElementsByTag("xml").first();
		
		Map<String, String> rep = new HashMap<String, String>();
		
		String appid = xml.getElementsByTag("appid").first().text();
		String bank_type = xml.getElementsByTag("bank_type").first().text();
		String cash_fee = xml.getElementsByTag("cash_fee").first().text();
		String fee_type = xml.getElementsByTag("fee_type").first().text();
		String is_subscribe = xml.getElementsByTag("is_subscribe").first().text();
		String mch_id = xml.getElementsByTag("mch_id").first().text();
		String nonce_str = xml.getElementsByTag("nonce_str").first().text();
		String openid = xml.getElementsByTag("openid").first().text();
		String out_trade_no = xml.getElementsByTag("out_trade_no").first().text();
		String result_code = xml.getElementsByTag("result_code").first().text();
		String return_code = xml.getElementsByTag("return_code").first().text();
		String sign = xml.getElementsByTag("sign").first().text();
		String time_end = xml.getElementsByTag("time_end").first().text();
		String total_fee = xml.getElementsByTag("total_fee").first().text();
		String trade_type = xml.getElementsByTag("trade_type").first().text();
		String transaction_id = xml.getElementsByTag("transaction_id").first().text();
		String attach = xml.getElementsByTag("attach").first().text();
		
		rep.put("appid", appid);
		rep.put("bank_type", bank_type);
		rep.put("cash_fee", cash_fee);
		rep.put("fee_type", fee_type);
		rep.put("is_subscribe", is_subscribe);
		rep.put("mch_id", mch_id);
		rep.put("nonce_str", nonce_str);
		rep.put("openid", openid);
		rep.put("out_trade_no", out_trade_no);
		rep.put("result_code", result_code);
		rep.put("return_code", return_code);
		rep.put("sign", sign);
		rep.put("time_end", time_end);
		rep.put("total_fee", total_fee);
		rep.put("trade_type", trade_type);
		rep.put("transaction_id", transaction_id);
		rep.put("attach", attach);
		
		return rep;
	}
	
	private String setXML(String return_code, String return_msg) {
		return "<xml><return_code><![CDATA[" + return_code
				+ "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";
	}
}